# -*- coding: utf-8 -*-

import sys
import re
import logging
from datetime import date, time, datetime

import pandas as pd

from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog
from PySide6.QtWidgets import QTableWidgetItem, QAbstractItemView

from MainWindow import Ui_MainWindow

class Attendance():
    def __init__(self):
        self.start_day = date.today()
        self.end_day = date.today()
        self.workClock0 = time(8, 0)
        self.workClock1 = time(12, 5)
        self.workClock2 = time(13, 10)
        self.workClock3 = time(14, 30)
        self.workClock4 = time(17, 5)

class AttendanceClock():
    def __init__(self, raw):
        self.raw = raw

class Staff():
    def __init__(self, userid):
        self.userid = userid
        self.name = ""
        self.attendanceClock = {}
        self.rest = {}
        self.vacate = {}
        self.firstClock = None
        self.second_Clock = None
        self.thirdClock = None
        self.forthClock = None

class Tool(QMainWindow):
    def __init__(self):
        super(Tool, self).__init__()
        self.version = "0.1"
        self.attendance = Attendance()
        self.staffs = []
        self.attendanceClock = [pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), pd.DataFrame()] # 打卡
        self.late = pd.DataFrame() # 迟到
        self.loss = pd.DataFrame() # 缺卡
        self.total = 0 # 员工总数
        self.file_name = ""
        self.dataFrameIndex = []
        self.dataFrameColumns = []

        self.mainWindow = Ui_MainWindow()
        self.mainWindow.setupUi(self)

        # 更新标题
        self.setWindowTitle("考勤工具_V" + self.version)
        self.mainWindow.tableWidget_attendance.setEditTriggers(QAbstractItemView.NoEditTriggers)
        
        # 按钮
        self.mainWindow.pushButton_importData.clicked.connect(self.importDataCallback)
        self.mainWindow.pushButton_exportData.clicked.connect(self.exportDataCallback)

    def getAttendanceClock(self, raw):
        attendanceClock = ["", "", "", ""]
        if raw != "":
            att_raw = raw.split("\n")
            att = list(set(att_raw))
            att.sort(key=att_raw.index)
            
            for line in att:
                line = line.strip()
                line = line + ":00"
                t = datetime.strptime(line, "%H:%M:%S").time()
                if t.__le__(self.attendance.workClock0):
                    if attendanceClock[0] == "":
                        attendanceClock[0] = t # 早晨打卡
                if t.__gt__(self.attendance.workClock0) and t.__lt__(self.attendance.workClock1):
                    if attendanceClock[0] == "":
                        attendanceClock[0] = "迟1次" # 迟到打卡
                if t.__ge__(self.attendance.workClock1) and t.__le__(self.attendance.workClock2):
                    if attendanceClock[1] == "":
                        attendanceClock[1] = t # 上午下班打开
                if t.__ge__(self.attendance.workClock2) and t.__le__(self.attendance.workClock3):
                    if not isinstance(attendanceClock[1], str) and attendanceClock[1].__eq__(time(13, 10)) and t.__eq__(self.attendance.workClock2):
                        pass # 中午仅在13:10打卡，算作上午下班打卡
                    else:
                        if attendanceClock[2] == "":
                            attendanceClock[2] = t # 下午上班
                if t.__gt__(self.attendance.workClock3) and t.__lt__(self.attendance.workClock4):
                    if attendanceClock[2] == "":
                        attendanceClock[2] = "迟1次" # 下午上班迟到
                if t.__ge__(self.attendance.workClock4):
                    attendanceClock[3] = t # 下午下班

        return attendanceClock

    def attendance2String(self, day_index, index):
        tmp = ""
        t = self.attendanceClock[0][day_index][index]
        if isinstance(t, str):
            tmp += t + "\n"
        else:
            tmp += t.strftime("%H:%M:%S")[:-3] + "\n"
        t = self.attendanceClock[1][day_index][index]
        if isinstance(t, str):
            tmp += t + "\n"
        else:
            tmp += t.strftime("%H:%M:%S")[:-3] + "\n"
        t = self.attendanceClock[2][day_index][index]
        if isinstance(t, str):
            tmp += t + "\n"
        else:
            tmp += t.strftime("%H:%M:%S")[:-3] + "\n"
        t = self.attendanceClock[3][day_index][index]
        if isinstance(t, str):
            tmp += t + ""
        else:
            tmp += t.strftime("%H:%M:%S")[:-3]

        loss_cnt = tmp.count("缺1次")
        late_cnt = tmp.count("迟1次")
        tmp = tmp.replace("缺1次\n", "").replace("缺1次", "").replace("迟1次\n", "").replace("迟1次", "") # 最后一行没有\n

        loss_str = ""
        late_str = ""
        if loss_cnt != 0:
            loss_str = "缺"+str(loss_cnt)+"次\n"
        if late_cnt != 0:
            late_str = "迟"+str(late_cnt)+"次\n"
        tmp = late_str + loss_str + tmp
        tmp = tmp.strip()

        return tmp

    def importDataCallback(self):
        file_name, _ = QFileDialog.getOpenFileName(self)
        logging.info("打开文件 " + file_name)
        self.file_name = file_name

        # 获取时间
        attendanceRaw = pd.read_excel(file_name, "打卡时间", header=None)
        time_sheet = attendanceRaw.values[0][0]
        tmp = re.split(" |：", time_sheet)
        start_day = datetime.strptime(tmp[2], "%Y-%m-%d")
        end_day = datetime.strptime(tmp[-1], "%Y-%m-%d")
        self.attendance.start_day = start_day.date()
        self.attendance.end_day = end_day.date()
        logging.debug("起始日期 " + start_day.strftime("%Y-%m-%d"))
        logging.debug("结束日期 " + end_day.strftime("%Y-%m-%d"))

        # 获取数据
        attendanceRaw = pd.read_excel(file_name, "打卡时间", header=2)

        self.total = len(attendanceRaw.values)

        # 修改索引
        attendanceRaw.set_index("姓名", inplace=True)
        new_columns = attendanceRaw.columns.to_list()
        for day in range(1, self.attendance.end_day.day - self.attendance.start_day.day + 1):
            new_columns[4+day] = str(day)
        attendanceRaw.columns = new_columns

        self.dataFrameIndex = attendanceRaw.index

        for i in range(4):
            self.attendanceClock[i].index = self.dataFrameIndex

        for day in range(1, self.attendance.end_day.day - self.attendance.start_day.day + 1):
            workClock = [[], [], [], []]
            tmp = attendanceRaw[str(day)]
            for index, clock in enumerate(tmp): # 计算每次打卡时间
                if isinstance(clock, str):
                    attendanceClock = self.getAttendanceClock(clock)
                else:
                    attendanceClock = ["", "", "", ""]
                attendanceClock = ["缺1次" if x=="" else x for x in attendanceClock]
                workClock[0].append(attendanceClock[0])
                workClock[1].append(attendanceClock[1])
                workClock[2].append(attendanceClock[2])
                workClock[3].append(attendanceClock[3])

            index = attendanceRaw.index
            self.attendanceClock[0][str(day)] = pd.Series(data=workClock[0], index=index)
            self.attendanceClock[1][str(day)] = pd.Series(data=workClock[1], index=index)
            self.attendanceClock[2][str(day)] = pd.Series(data=workClock[2], index=index)
            self.attendanceClock[3][str(day)] = pd.Series(data=workClock[3], index=index)

        for day in range(self.attendance.start_day.day, self.attendance.end_day.day + 1):
            self.dataFrameColumns.append(str(day))

        self.mainWindow.tableWidget_attendance.setColumnCount(36)
        self.mainWindow.tableWidget_attendance.setRowCount(self.total)
        self.mainWindow.tableWidget_attendance.clearContents()
        self.mainWindow.tableWidget_attendance.setHorizontalHeaderLabels(self.dataFrameColumns)
        self.mainWindow.tableWidget_attendance.setVerticalHeaderLabels(self.dataFrameIndex.to_list())
        for day in range(1, self.attendance.end_day.day - self.attendance.start_day.day + 1):
            day_index = str(day)
            for i in range(self.total):
                tmp = self.attendance2String(day_index, i)
                itm_attendance = QTableWidgetItem(tmp)
                self.mainWindow.tableWidget_attendance.setItem(i, day-1, itm_attendance)
        
        self.mainWindow.tableWidget_attendance.resizeRowsToContents()

    def exportDataCallback(self):

        tmp1 = pd.DataFrame()
        tmp1.index = self.attendanceClock[0].index
        for day in range(1, self.attendance.end_day.day - self.attendance.start_day.day + 1):
            day_index = str(day)
            tmp_list = []
            for i in range(self.total):
                tmp = self.attendance2String(day_index, i)
                tmp_list.append(tmp)

            tmp_series = pd.Series(data=tmp_list, index=self.attendanceClock[0].index)
            tmp1[str(day+self.attendance.start_day.day-1)] =  tmp_series

        file_name, _ = QFileDialog.getSaveFileName(self, ".xlsx")
        logging.info("写入文件 " + file_name)
        writer = pd.ExcelWriter(file_name)
        tmp1.to_excel(writer, sheet_name="考勤")
        writer.close()

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    app = QApplication(sys.argv)
    tool = Tool()
    tool.show()
    sys.exit(app.exec())